package com.sdry.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;

public class SerialComm4MainWindows {
	public SerialComm4MainWindows() {
		super();
	}

	private static SerialPort serialPort;

	public void connect(String portName) throws Exception {
		CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
		if (portIdentifier.isCurrentlyOwned()) {
			System.out.println("Error: Port is currently in use");
		} else {
			CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
			if (commPort instanceof SerialPort) {
				serialPort = (SerialPort) commPort;
				serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);


				InputStream in = serialPort.getInputStream();
				(new Thread(new SerialReader(in))).start();
				byte[] buffer = new byte[1024];
//				System.out.println("=======111111======"+in.read(buffer));
			} else {
				System.out.println("Error: Only serial ports are handled by this example.");
			}
		}
	}


	/** 读串口数据*/
	public class SerialReader implements Runnable {
		InputStream in;


		public SerialReader(InputStream in) {
			this.in = in;
		}


		public void run() {
			byte[] buffer = new byte[999999999];
			int len = -1;
			try {
				while ((len = this.in.read(buffer)) > -1) {
					String getValue = new String(buffer, 0, len);
					if(getValue != null && getValue.length() > 2) {
						//获取值往另一个地方丢
						serialPort.close();
						ApplicationContextHelper.test(getValue);
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}


	/** */
	public static class SerialWriter implements Runnable {
		OutputStream out;


		public SerialWriter(OutputStream out) {
			this.out = out;
		}


		public void run() {
			try {
				int c = 0;
				while ((c = System.in.read()) > -1) {
					this.out.write(c);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @param name 串口名称
	 * @param regionName 缺料区域
	 * @param stockNum 物料编码
	 * @param stockName 物料名称
	 * @param stockModel 物料规格型号
	 * @param paunit 物料单位
	 * @param packNorm 物料规格
	 * @param batch 批次号
	 * @param quantity 物料数量
	 * @param productionOrder 排产单号
	 * @param type 领料情况（1线边库叫料2排产单叫料）
	 */
	public static void sendMsg(String name,String regionName,String stockNum,String stockName,String stockModel,
			String paunit,String packNorm,String batch,String quantity,String type,String productionOrder){
		//枚举类型，获取所有的通行端口，包括232（PORT_SERIAL）、485、并口等等
		Enumeration enumeration= CommPortIdentifier.getPortIdentifiers();

		while (enumeration.hasMoreElements()){
	        //判断enumeration里面是否有更多的元素

	        //获取下一个元素，该元素包含某个通信端口的所有信息
	        CommPortIdentifier commPortIdentifier= (CommPortIdentifier) enumeration.nextElement();

	        //如果该端口的类型是串口
	        if (commPortIdentifier.getPortType()==CommPortIdentifier.PORT_SERIAL){

	            //判断该串口的名称
	            if (commPortIdentifier.getName().equals(name)){
	                try {
	                    //打开串口，获得该串口的serialPort对象
	                    SerialPort serialPort=
	                            (SerialPort) commPortIdentifier.open("",2000);

	                    //设置该串口参数，9600,8,1,n
	                    serialPort.setSerialPortParams(9600,8,1,0);

	                    //获取输出流，利用输出流发送数据
	                    OutputStream outputStream=serialPort.getOutputStream();
	                    if ("1".equals(type)) {
	                    	/*outputStream.write(("手动叫料"+regionName+"材料编号:"+stockNum+"材料名称:"+stockName+
	                    			"规格型号:"+stockModel+"主计量单位:"+paunit+"包装规格:"+
	                    			packNorm+"批次号:"+batch+"数量:"+quantity).getBytes("GB2312"));*/
	                    	outputStream.write(("1,"+stockNum+","+batch+","+quantity+",0;").getBytes("GB2312"));
						} else {
							/*outputStream.write(("排产单叫料"+regionName+"材料编号:"+stockNum+"材料名称:"+stockName+
	                    			"规格型号:"+stockModel+"主计量单位:"+paunit+"包装规格:"+
	                    			packNorm+"批次号:"+batch+"数量:"+quantity+"排产单:"+productionOrder).getBytes("GB2312"));*/
							outputStream.write(("1,"+stockNum+","+batch+","+quantity+","+productionOrder+";").getBytes("GB2312"));
						}
                    	//outputStream.write("/n".getBytes());
	                    //一定要关闭串口，否则会阻塞该串口，直到你关闭程序
	                    serialPort.close();
	                    outputStream.close();

	                } catch (PortInUseException e) {
	                    System.out.println("PortInUseException抛出，串口被使用");
	                    e.printStackTrace();
	                } catch (UnsupportedCommOperationException e) {
	                    System.out.println("UnsupportedCommOperationException抛出");
	                    e.printStackTrace();
	                } catch (IOException e) {
	                    System.out.println("IOException抛出");
	                    e.printStackTrace();
	                }
	            }
	        }
	    }
	}

	public static void main(String[] args) {
		try {
			(new SerialComm4MainWindows()).connect("COM3");
			//sendMsg("COM3", "1", "2", "3", "4", "5", "6", "7", 8, "9", "10");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
